﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using WinFormAssigment.BUS;
using WinFormAssigment.DAO;
using WinFormAssigment.Entities;

namespace WinFormAssigment.GUI
{
    public partial class ClassManager : Form
    {
        public ClassManager()
        {
            InitializeComponent();
            txtTeacherPass.PasswordChar = '*';
        }
        List<Teacher> listTeacher;
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            EnablePanelControl();
        }

        private void EnablePanelControl()
        {
            if (tabControl1.SelectedIndex == 0)
            {
                pnlClass.Visible = true;
                pnlStudent.Visible = false;
                pnlTeacher.Visible = false;
                pnlTeacherControl.Visible = false;
                pnlClassControl.Visible = true;
                pnlStudentControl.Visible = false;
            }
            else if (tabControl1.SelectedIndex == 1)
            {
                pnlClass.Visible = false;
                pnlStudent.Visible = false;
                pnlTeacher.Visible = true;
                pnlTeacherControl.Visible = true;
                pnlClassControl.Visible = false;
                pnlStudentControl.Visible = false;
            }
            else if (tabControl1.SelectedIndex == 2)
            {
                pnlClass.Visible = false;
                pnlStudent.Visible = true;
                pnlTeacher.Visible = false;
                pnlTeacherControl.Visible = false;
                pnlClassControl.Visible = false;
                pnlStudentControl.Visible = true;
                //pnlClass.Visible = false;
                //pnlTeacher.Visible = false;
            }
        }
        private void EnableTeacherControl()
        {
            cbbClassID.Enabled = false;
            cbbTeacherID.Enabled = false;
            btnTeacherControlSave.Enabled = false;
            btnTeacherControlUpdate.Enabled = false;
            btnTeacherControlRefresh.Enabled = false;
            btnTeacherSavePicture.Enabled = false;
            btnTeacherChangePicture.Enabled = false;
            txtTeacherID.Enabled = false;
        }

        private void ClassManager_Load(object sender, EventArgs e)
        {
            EnablePanelControl();
            EnableTeacherControl();
            listTeacher = TeacherControl.GetAllTeacher();
            FillGrvwTeacher(listTeacher);
            DataTable table = ClassControl.GetClassInformation();
            FillLvwClassInformation(table);
            rbtnFemale.Checked = true;
            rbtnMale.Checked = false;
            toolStripClassDetail.Enabled = false;
            EnableClassControlPabel();
            FillCbbTeacherIDClassControlPanel();
            EnableStudentControl();
            FillTreeViewStudentClassID();
            grbStudentAvatar.Enabled = false;
        }


        private void btnNewClassTeacher_Click(object sender, EventArgs e)
        {
            if (btnNewClassTeacher.Text == "New Class")
            {
                btnNewClassTeacher.Text = "Save";
                cbbClassID.Enabled = true;
                cbbTeacherID.Enabled = true;
                List<Class> listClass = ClassControl.GetAllClass();
                foreach (Class c in listClass)
                {
                    cbbClassID.Items.Add(c.ClassID);
                }
                listTeacher = TeacherControl.GetAllTeacher();
                foreach (Teacher t in listTeacher)
                {
                    cbbTeacherID.Items.Add(t.TeacherID);
                }
            }
            else if (btnNewClassTeacher.Text == "Save")
            {
                btnNewClassTeacher.Text = "New Class";
                cbbClassID.Enabled = false;
                cbbTeacherID.Enabled = false;
                MessageBox.Show("Sorry: Unfinish Function Button !", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }


        private void btnSavePicture_Click(object sender, EventArgs e)
        {
            bool b = !Validation.IsEmptyTextBox(new TextBox[] { txtTeacherPicture, txtTeacherID });
            if (b)
            {
                string teacherID = txtTeacherID.Text;
                bool existTeacherID = TeacherControl.ExistTeacheIDAvatar(teacherID);
                if (existTeacherID)
                {
                    UpdateTeacherAvatar(teacherID);
                }
                else
                {
                    InsertTeacherAvatar(teacherID);
                }
                txtTeacherPicture.Text = "";
            }
            else MessageBox.Show("Filebath or TeacherID must be not empty !", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        private void InsertTeacherAvatar(string teacherID)
        {
            string fileBath = txtTeacherPicture.Text;
            byte[] imageByte = null;
            using (FileStream fs = new FileStream(fileBath, FileMode.Open, FileAccess.Read))
            {
                imageByte = new byte[fs.Length];
                fs.Read(imageByte, 0, (int)fs.Length);
            }
            bool result = TeacherControl.InsertTeacherAvatar(teacherID, imageByte);
            if (result)
            {
                MessageBox.Show("Save Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Save Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void UpdateTeacherAvatar(string teacherID)
        {
            string fileBath = txtTeacherPicture.Text;
            byte[] image = null;
            using (FileStream fs = new FileStream(fileBath, FileMode.Open, FileAccess.Read))
            {
                image = new byte[fs.Length];
                fs.Read(image, 0, (int)fs.Length);
            }
            bool result = TeacherControl.UpdateTeacherAvatar(teacherID, image);
            if (result)
            {
                MessageBox.Show("Save Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Save Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillGrvwTeacher(List<Teacher> list)
        {
            DataTable table = new DataTable();
            int rol = 1;
            table.Columns.Add("Roll");
            table.Columns.Add("Teacher ID");
            table.Columns.Add("Real Name");
            table.Columns.Add("Gender");
            table.Columns.Add("Email");
            table.Columns.Add("Phone");
            foreach (Teacher t in list)
            {
                DataRow row = table.NewRow();
                row[0] = rol;
                row[1] = t.TeacherID;
                row[2] = t.Name;
                row[3] = t.Gender;
                row[4] = t.Email;
                row[5] = t.Phone;
                table.Rows.Add(row);
                rol++;
            }
            grvwTeacher.DataSource = table;
            grvwTeacher.Columns[0].Width = 35;
            grvwTeacher.Columns[1].Width = 100;
            grvwTeacher.Columns[2].Width = 150;
            grvwTeacher.Columns[3].Width = 60;
            grvwTeacher.Columns[4].Width = 200;
            grvwTeacher.Columns[5].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void btnAddTeacher_Click(object sender, EventArgs e)
        {
            pbAvatar.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, @"Images\avatarDefault.png");
            btnTeacherChangePicture.Enabled = false;
            btnTeacherSavePicture.Enabled = true;
            btnTeacherControlSave.Enabled = true;
            btnTeacherControlRefresh.Enabled = true;
            btnTeacherControlUpdate.Enabled = false;
            RefreshTeacherInformation();
            txtTeacherID.Enabled = true;
        }

        private void grvwTeacher_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex > -1 && e.RowIndex < grvwTeacher.Rows.Count)
            {
                DataGridViewRow row = grvwTeacher.Rows[e.RowIndex];
                string teacherID = row.Cells[1].Value.ToString();
                FillTeacherInformation(teacherID);
                string txt = txtTeacherID.Text;
                ShowTeacherAvatar(txt);
                EnableTeacherControl();
            }
        }
        private void FillTeacherInformation(string teacherID)
        {
            foreach (Teacher t in listTeacher)
            {
                if (t.TeacherID == teacherID)
                {
                    txtTeacherID.Text = t.TeacherID;
                    txtTeacherPass.Text = t.Password;
                    txtTeacherName.Text = t.Name;
                    if (t.Gender.ToLower() == "male")
                    {
                        rbtnMale.Checked = true;
                        rbtnFemale.Checked = false;
                    }
                    else if (t.Gender.ToLower() == "female")
                    {
                        rbtnMale.Checked = false;
                        rbtnFemale.Checked = true;
                    }
                    dtpTeacherBirthday.Value = t.Dob;
                    txtTeacherEmail.Text = t.Email;
                    txtTeacherPhone.Text = t.Phone;
                    rtxtTeacherAddress.Text = t.Address;
                    rtxtTeacherDescription.Text = t.Description;
                }
            }
        }
        private void ShowTeacherAvatar(string teacherID)
        {
            byte[] img = TeacherControl.GetTeacherAvatar(teacherID);
            if (img != null)
            {
                MemoryStream stream = new MemoryStream(img);
                pbAvatar.Image = Image.FromStream(stream);
            }
            else
            {
                pbAvatar.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, @"Images\avatarDefault.png");
            }
        }

        private void btnTeacherChangePicture_Click(object sender, EventArgs e)
        {
            Stream stream;
            openDialog = new OpenFileDialog();
            openDialog.Filter = "All Images (*.bmp;*.gif;*.png;*.jpg)|*.bmp;*.gif;*.png;*.jpg|bitmap|*.bmp|gifs|*.gif|png|*.png|jpeg|*.jpg";
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                stream = openDialog.OpenFile();
                if (stream != null)
                {
                    string filebath = openDialog.FileName;
                    txtTeacherPicture.Text = filebath;
                    pbAvatar.Image = Image.FromFile(filebath);
                }
            }
        }

        private void btnTeacherControlRefresh_Click(object sender, EventArgs e)
        {
            RefreshTeacherInformation();
        }

        private void RefreshTeacherInformation()
        {
            if (btnTeacherControlSave.Enabled == true)
            {
                txtTeacherID.Text = "";
                txtTeacherPass.Text = "";
                txtTeacherName.Text = "";
                rbtnFemale.Checked = true;
                rbtnMale.Checked = false;
                txtTeacherEmail.Text = "";
                txtTeacherPhone.Text = "";
                rtxtTeacherAddress.Text = "";
                rtxtTeacherDescription.Text = "";
                dtpTeacherBirthday.Value = DateTime.Now;
            }
            else
            {
                txtTeacherPass.Text = "";
                txtTeacherName.Text = "";
                rbtnFemale.Checked = false;
                rbtnMale.Checked = false;
                txtTeacherEmail.Text = "";
                txtTeacherPhone.Text = "";
                rtxtTeacherAddress.Text = "";
                rtxtTeacherDescription.Text = "";
                dtpTeacherBirthday.Value = DateTime.Now;
            }
        }

        private void btnUpdateTeacher_Click(object sender, EventArgs e)
        {
            int index = grvwTeacher.CurrentRow.Index;
            DataGridViewRow row = grvwTeacher.Rows[index];
            string teacherID = row.Cells["Teacher ID"].Value.ToString();
            DialogResult result = MessageBox.Show("Do you want to update teacher : " + teacherID, "Message Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                if (txtTeacherID.Text.Trim().Length == 0)
                {
                    FillTeacherInformation(teacherID);
                    ShowTeacherAvatar(teacherID);
                }
                else
                {
                    FillTeacherInformation(teacherID);
                    ShowTeacherAvatar(teacherID);
                }
                btnTeacherChangePicture.Enabled = true;
                btnTeacherSavePicture.Enabled = true;
                btnTeacherControlSave.Enabled = false;
                btnTeacherControlRefresh.Enabled = true;
                btnTeacherControlUpdate.Enabled = true;
                txtTeacherID.Enabled = false;
            }
        }

        private void btnDeleteTeacher_Click(object sender, EventArgs e)
        {
            int index = grvwTeacher.CurrentRow.Index;
            DataGridViewRow row = grvwTeacher.Rows[index];
            string teacherID = row.Cells["Teacher ID"].Value.ToString();
            DialogResult result = MessageBox.Show("Do you want to delete teacher: " + teacherID + "?", "Message Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                bool existTeacherID = TeacherControl.ExistTeacheIDAvatar(teacherID);
                if (!existTeacherID)
                {
                    bool b = TeacherControl.DeleteTeacher(teacherID);
                    if (b)
                    {
                        MessageBox.Show("Delete Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Delete Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    bool b1 = TeacherControl.DeleteTeacherAvatar(teacherID);
                    bool b2 = TeacherControl.DeleteTeacher(teacherID);
                    if (b1 && b2)
                    {
                        MessageBox.Show("Delete Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        MessageBox.Show("Delete Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            listTeacher = TeacherControl.GetAllTeacher();
            FillGrvwTeacher(listTeacher);
        }

        private bool ValidationTeacherTextbox()
        {
            TextBox[] arrTxt = { txtTeacherID, txtTeacherPass, txtTeacherName, txtTeacherEmail, txtTeacherPhone };
            RichTextBox[] arrRtxt = { rtxtTeacherAddress, rtxtTeacherDescription };
            bool b1 = !Validation.IsEmptyTextBox(arrTxt);
            bool b2 = !Validation.IsEmptyRichTextBox(arrRtxt);
            return b1 && b2;
        }
        private Teacher TeacherInformaion(string gender)
        {
            string id, pass, name, address, email, phone, des;
            DateTime dob;
            id = txtTeacherID.Text.ToLower();
            pass = txtTeacherPass.Text.ToLower();
            name = txtTeacherName.Text;
            dob = dtpTeacherBirthday.Value;
            address = rtxtTeacherAddress.Text;
            email = txtTeacherEmail.Text;
            phone = txtTeacherPhone.Text;
            des = rtxtTeacherDescription.Text;
            Teacher t = new Teacher()
            {
                TeacherID = id,
                Password = pass,
                Name = name,
                Gender = gender,
                Dob = dob,
                Address = address,
                Email = email,
                Phone = phone,
                Description = des
            };
            return t;
        }

        private void btnTeacherControlSave_Click(object sender, EventArgs e)
        {
            if (ValidationTeacherTextbox())
            {
                if (Validation.ValidationTeacherDOB(dtpTeacherBirthday.Value))
                {
                    string phone = txtTeacherPhone.Text;
                    if (Validation.IsPhoneNumber(phone))
                    {
                        string email = txtTeacherEmail.Text;
                        if (Validation.IsValidEmail(email))
                        {
                            string gender;
                            if (rbtnFemale.Checked)
                            {
                                gender = rbtnFemale.Text.ToLower();
                            }
                            else
                            {
                                gender = rbtnMale.Text.ToLower();
                            }
                            Teacher t = TeacherInformaion(gender);
                            bool b = TeacherControl.InsertTeacher(t);
                            if (b)
                            {
                                MessageBox.Show("Add Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                btnTeacherControlSave.Enabled = false;
                                btnTeacherControlUpdate.Enabled = true;
                                btnTeacherChangePicture.Enabled = true;
                                txtTeacherID.Enabled = false;
                                listTeacher = TeacherControl.GetAllTeacher();
                                FillGrvwTeacher(listTeacher);
                            }
                            else
                            {
                                MessageBox.Show(" Add Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else MessageBox.Show("Email is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else MessageBox.Show("Phone Number is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else MessageBox.Show("Birthday is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("TextBox must be not empty", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnTeacherControlUpdate_Click(object sender, EventArgs e)
        {
            if (ValidationTeacherTextbox())
            {
                if (Validation.ValidationTeacherDOB(dtpTeacherBirthday.Value))
                {
                    string phone = txtTeacherPhone.Text;
                    if (Validation.IsPhoneNumber(phone))
                    {
                        string email = txtTeacherEmail.Text;
                        if (Validation.IsValidEmail(email))
                        {
                            string gender;
                            if (rbtnFemale.Checked)
                            {
                                gender = rbtnFemale.Text.ToLower();
                            }
                            else
                            {
                                gender = rbtnMale.Text.ToLower();
                            }
                            Teacher t = TeacherInformaion(gender);
                            bool b = TeacherControl.UpdateTeacher(t);
                            if (b)
                            {
                                MessageBox.Show("Update Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                btnTeacherControlSave.Enabled = false;
                                btnTeacherControlUpdate.Enabled = true;
                                txtTeacherID.Enabled = false;
                                listTeacher = TeacherControl.GetAllTeacher();
                                FillGrvwTeacher(listTeacher);
                            }
                            else
                            {
                                MessageBox.Show("Update Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else MessageBox.Show("Email is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else MessageBox.Show("Phone Number is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else MessageBox.Show("Birthday is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("TextBox must be not empty", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        private void btnRefreshTeacher_Click(object sender, EventArgs e)
        {
            listTeacher = TeacherControl.GetAllTeacher();
            FillGrvwTeacher(listTeacher);
        }

        private void btnSearchTeacher_Click(object sender, EventArgs e)
        {
            string teacherName = txtTeacherSearch.Text;
            List<Teacher> list = TeacherControl.SearchTeacherByName(teacherName);
            FillGrvwTeacher(list);

        }

        private void btnHistoryTeacher_Click(object sender, EventArgs e)
        {
            int index = grvwTeacher.CurrentRow.Index;
            DataGridViewRow row = grvwTeacher.Rows[index];
            string teacherID = row.Cells["Teacher ID"].Value.ToString();
            grvwTeacher.DataSource = TeacherControl.GetClassHistoryByTeacherID(teacherID);

        }

        private void btnTeacherHistory_Click(object sender, EventArgs e)
        {
            string teacherID = txtTeacherID.Text;
            if (teacherID.Trim().Length > 0)
            {
                grvwTeacher.DataSource = TeacherControl.GetClassHistoryByTeacherID(teacherID);
            }
        }

        private void txtTeacherSearch_MouseDown(object sender, MouseEventArgs e)
        {
            txtTeacherSearch.Text = "";
        }

        private void FillLvwClassInformation(DataTable table)
        {
            lvwClassInformation.Items.Clear();
            if (table.Rows.Count > 0)
            {
                int index = 0;
                int roll = 0;
                foreach (DataRow row in table.Rows)
                {
                    roll += 1;
                    string classID = row["ClassID"].ToString();
                    string teacherName = row["Teacher Name"].ToString();
                    string timeSlot = row["TimeSlot"].ToString();
                    string room = row["Room"].ToString();
                    string totalStudent = row["Total Student"].ToString();
                    lvwClassInformation.Items.Add(roll.ToString());
                    lvwClassInformation.Items[index].SubItems.Add(classID);
                    lvwClassInformation.Items[index].SubItems.Add(totalStudent);
                    lvwClassInformation.Items[index].SubItems.Add(teacherName);
                    lvwClassInformation.Items[index].SubItems.Add(timeSlot);
                    lvwClassInformation.Items[index].SubItems.Add(room);
                    index++;
                }
            }
            else
            {
                lvwClassInformation.Items.Clear();
            }
        }
        private void FillTreeViewClassDetail()
        {
            trwClassDetail.Nodes.Clear();
            List<string> AllID = ClassControl.GetAllClassID();
            trwClassDetail.Nodes.Add("All Classes");
            foreach (string classID in AllID)
            {
                trwClassDetail.Nodes[0].Nodes.Add(classID);
            }
            trwClassDetail.Nodes.Add("Learning Classes");
            List<string> learningIDs = ClassControl.GetClassIDLearning();
            foreach (string classID in learningIDs)
            {
                trwClassDetail.Nodes[1].Nodes.Add(classID);
            }
            trwClassDetail.Nodes.Add("Waiting Classes");
            List<string> waitingIDs = ClassControl.GetClassIDWaiting();
            foreach (string classID in waitingIDs)
            {
                trwClassDetail.Nodes[2].Nodes.Add(classID);
            }
            trwClassDetail.Nodes.Add("Finished Classes");
            List<string> finishedIDs = ClassControl.GetClassIDFinished();
            foreach (string classID in finishedIDs)
            {
                trwClassDetail.Nodes[3].Nodes.Add(classID);
            }
        }
        private void FillGrvwClassDetail(string classID)
        {
            DataTable table = ClassControl.GetClassHistoryByClassID(classID);
            grvwClassDetail.DataSource = table;
            grvwClassDetail.Columns[0].Width = 100;
            grvwClassDetail.Columns[1].Width = 150;
            grvwClassDetail.Columns[2].Width = 100;
            grvwClassDetail.Columns[3].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl2.SelectedIndex == 0)
            {
                DataTable table = ClassControl.GetClassInformation();
                FillLvwClassInformation(table);

            }
            else if (tabControl2.SelectedIndex == 1)
            {
                FillTreeViewClassDetail();

            }
        }

        private void trwClassDetail_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = trwClassDetail.SelectedNode;
            if (node.Level == 1)
            {
                grvwClassDetail.Columns.Clear();
                string classID = node.Text.ToString();
                FillGrvwClassDetail(classID);
                List<string> list = ClassControl.GetClassTimeStartAndTimeEnd(classID);
                txtClassDetailClassID.Text = classID;
                txtClassDetailTimeStart.Text = list[0];
                txtClassDetailTimeEnd.Text = list[1];
                toolStripClassDetail.Enabled = true;
                FillLvwStudentClassDetail(classID);
                pnlClassControlPanel.Enabled = true;
                Class c = ClassControl.GetClassByClassID(classID);
                FillClassInformation(c);
                EnableClassControlPabel();
            }
            else if (node.Level == 0)
            {
                FillGrvwClassDetail("");
                toolStripClassDetail.Enabled = false;
                txtClassDetailClassID.Text = "";
                txtClassDetailTimeStart.Text = "";
                txtClassDetailTimeEnd.Text = "";
                pnlClassControlPanel.Enabled = false;
            }
        }
        private void FillLvwStudentClassDetail(string classID)
        {
            lvwClassDetailStudent.Items.Clear();
            DataTable table = ClassControl.GetClassDetailStudent(classID);
            if (table.Rows.Count > 0)
            {
                int roll = 1;
                int index = 0;
                foreach (DataRow row in table.Rows)
                {
                    string studentID = row["StudentID"].ToString();
                    string studentName = row["Name"].ToString();
                    string status = row["Status"].ToString();
                    lvwClassDetailStudent.Items.Add(roll.ToString());
                    lvwClassDetailStudent.Items[index].SubItems.Add(studentID);
                    lvwClassDetailStudent.Items[index].SubItems.Add(studentName);
                    lvwClassDetailStudent.Items[index].SubItems.Add(status);
                    roll += 1;
                    index += 1;
                }
            }
        }
        private void EnableClassControlPabel()
        {
            btnChangeTeacherClassControlPanel.Enabled = false;
            btnUpdateClassControlPanel.Enabled = false;
            btnAddClassControlPanel.Enabled = false;
            btnRefreshClassControlPanel.Enabled = false;
            cbbTeacherIDClassControlPanel.Enabled = false;
            dtpTimeStartClassControlPanel.Enabled = false;
            dtpTimeEndClassControlPanel.Enabled = false;
        }
        private void FillCbbTeacherIDClassControlPanel()
        {
            List<string> list = TeacherControl.GetAllTeacherID();
            cbbTeacherIDClassControlPanel.DataSource = list;
        }
        private void FillClassInformation(Class c)
        {
            txtClassIDClassControlPanel.Text = c.ClassID;
            txtRoomClassControlPanel.Text = c.Room;
            txtClassNameClassControlPanel.Text = c.Name;
            txtTimeSlotClassControlPanel.Text = c.TimeSlot;
            txtRoomClassControlPanel.Text = c.Room;
            dtpTimeStartClassControlPanel.Value = c.TimeStart;
            dtpTimeEndClassControlPanel.Value = c.TimeEnd;
            cbbTeacherIDClassControlPanel.SelectedItem = c.TeacherID;
            ShowTeacherAvatarClassControlPanel(c.TeacherID);
            txtClassIDClassControlPanel.Enabled = false;
        }
        private void ShowTeacherAvatarClassControlPanel(string teacherID)
        {
            byte[] img = TeacherControl.GetTeacherAvatar(teacherID);
            if (img != null)
            {
                MemoryStream stream = new MemoryStream(img);
                pbTeacherAvatarClassControlPanel.Image = Image.FromStream(stream);
            }
            else
            {
                pbTeacherAvatarClassControlPanel.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, @"Images\avatarDefault.png");
            }
        }
        private void btnAddNewClass_Click(object sender, EventArgs e)
        {
            txtClassIDClassControlPanel.Text = "";
            txtClassNameClassControlPanel.Text = "";
            txtTimeSlotClassControlPanel.Text = "";
            txtRoomClassControlPanel.Text = "";
            txtClassIDClassControlPanel.Enabled = true;
            cbbTeacherIDClassControlPanel.Enabled = true;
            dtpTimeStartClassControlPanel.Enabled = true;
            dtpTimeEndClassControlPanel.Enabled = true;
            pbTeacherAvatarClassControlPanel.ImageLocation = Path.Combine(System.Windows.Forms.Application.StartupPath, @"Images\avatarDefault.png");
            btnAddClassControlPanel.Enabled = true;
            btnRefreshClassControlPanel.Enabled = true;
            btnUpdateClassControlPanel.Enabled = false;
            btnChangeTeacherClassControlPanel.Enabled = false;
            dtpTimeStartClassControlPanel.Value = DateTime.Now;
            dtpTimeEndClassControlPanel.Value = DateTime.Now;
            txtTimeSlotClassControlPanel.Enabled = false;
            cbbTimeSlot.SelectedIndex = 0;
        }

        private void btnAddClassControlPanel_Click(object sender, EventArgs e)
        {
            TextBox[] arrtxt = { txtClassIDClassControlPanel, txtClassNameClassControlPanel, txtTimeSlotClassControlPanel, txtRoomClassControlPanel };
            bool b = !Validation.IsEmptyTextBox(arrtxt);
            if (b)
            {
                string classID = txtClassIDClassControlPanel.Text;
                string className = txtClassNameClassControlPanel.Text;
                string timeSlot = txtTimeSlotClassControlPanel.Text;
                string room = txtRoomClassControlPanel.Text;
                DateTime start = dtpTimeStartClassControlPanel.Value;
                DateTime end = dtpTimeEndClassControlPanel.Value;
                if (end > start)
                {
                    string teacherID = cbbTeacherIDClassControlPanel.SelectedItem.ToString();
                    if (teacherID.Trim().Length > 0)
                    {
                        Class c = new Class()
                        {
                            ClassID = classID,
                            Name = className,
                            TimeStart = start,
                            TimeEnd = end,
                            TeacherID = teacherID,
                            TimeSlot = timeSlot,
                            Room = room
                        };
                        bool bo = ClassControl.InsertClass(c);
                        if (bo)
                        {
                            bool boo = ClassControl.InsertClassHistory(new ClassHistory()
                            {
                                ClassID = classID,
                                TeacherID = teacherID,
                                TeachTimeStart = start
                            });
                            if (boo)
                            {
                                MessageBox.Show("Add Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                FillTreeViewClassDetail();
                            }
                            else
                            {
                                MessageBox.Show("Add Class History Failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        else
                        {
                            MessageBox.Show("Add failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                else
                {
                    MessageBox.Show("TimeStart and TimeEnd is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("TextBox must be not empty", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cbbTimeSlot_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtTimeSlotClassControlPanel.Text = cbbTimeSlot.SelectedItem.ToString().ToLower();
        }

        private void btnRefreshClassControlPanel_Click(object sender, EventArgs e)
        {
            if (btnAddClassControlPanel.Enabled == true)
            {
                txtClassIDClassControlPanel.Text = "";
                txtRoomClassControlPanel.Text = "";
                txtClassNameClassControlPanel.Text = "";
                txtTimeSlotClassControlPanel.Text = "";
                txtRoomClassControlPanel.Text = "";
                dtpTimeStartClassControlPanel.Value = DateTime.Now;
                dtpTimeEndClassControlPanel.Value = DateTime.Now;
                cbbTeacherIDClassControlPanel.SelectedIndex = 0;
                ShowTeacherAvatarClassControlPanel("");
            }
            else if (btnUpdateClassControlPanel.Enabled == true)
            {
                txtClassIDClassControlPanel.Text = "";
                txtRoomClassControlPanel.Text = "";
                txtClassNameClassControlPanel.Text = "";
                txtTimeSlotClassControlPanel.Text = "";
                txtRoomClassControlPanel.Text = "";
                txtTimeSlotClassControlPanel.Enabled = false;
            }
        }

        private void btnUpdateClass_Click(object sender, EventArgs e)
        {
            string classID = txtClassIDClassControlPanel.Text;
            FillGrvwClassDetail(classID);
            if (txtClassIDClassControlPanel.Text.Trim().Length > 0)
            {
                DialogResult result = MessageBox.Show("Do you want to update Class : " + classID, "Message Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    txtClassIDClassControlPanel.Enabled = false;
                    txtTimeSlotClassControlPanel.Enabled = false;
                    cbbTeacherIDClassControlPanel.Enabled = false;
                    btnAddClassControlPanel.Enabled = false;
                    btnUpdateClassControlPanel.Enabled = true;
                    btnRefreshClassControlPanel.Enabled = true;
                    btnChangeTeacherClassControlPanel.Enabled = false;
                    dtpTimeStartClassControlPanel.Enabled = true;
                    dtpTimeEndClassControlPanel.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("You must to choose ClassID in Class Treeview", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnUpdateClassControlPanel_Click(object sender, EventArgs e)
        {
            TextBox[] arrtxt = { txtClassIDClassControlPanel, txtClassNameClassControlPanel, txtTimeSlotClassControlPanel, txtRoomClassControlPanel };
            bool b = !Validation.IsEmptyTextBox(arrtxt);
            if (b)
            {
                string classID = txtClassIDClassControlPanel.Text;
                string className = txtClassNameClassControlPanel.Text;
                string timeSlot = txtTimeSlotClassControlPanel.Text;
                string room = txtRoomClassControlPanel.Text;
                DateTime start = dtpTimeStartClassControlPanel.Value;
                DateTime end = dtpTimeEndClassControlPanel.Value;
                if (end > start)
                {
                    Class c = new Class()
                    {
                        ClassID = classID,
                        Name = className,
                        TimeStart = start,
                        TimeEnd = end,
                        TimeSlot = timeSlot,
                        Room = room
                    };
                    bool bo = ClassControl.UpdateClass(c);
                    if (bo)
                    {
                        MessageBox.Show("Add Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        FillTreeViewClassDetail();
                    }
                    else
                    {
                        MessageBox.Show("Add failure", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
                else
                {
                    MessageBox.Show("TimeStart and TimeEnd is wrong", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("TextBox must be not empty", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteClass_Click(object sender, EventArgs e)
        {
            string classID = txtClassIDClassControlPanel.Text;
            FillGrvwClassDetail(classID);
            if (txtClassIDClassControlPanel.Text.Trim().Length > 0)
            {
                MessageBox.Show("Empty Button", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("You must to choose ClassID in Class Treeview", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void btnClassDetailChangeTeacher_Click(object sender, EventArgs e)
        {
            string classID = txtClassIDClassControlPanel.Text;
            FillGrvwClassDetail(classID);
            if (txtClassIDClassControlPanel.Text.Trim().Length > 0)
            {
                DialogResult result = MessageBox.Show("Do you want to change teacher class : " + classID, "Message Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    lblCurrentTeacher.Text = cbbTeacherIDClassControlPanel.SelectedItem.ToString();
                    dtpTimeSource.Value = dtpTimeStartClassControlPanel.Value;
                    cbbTeacherIDClassControlPanel.Enabled = true;
                    btnChangeTeacherClassControlPanel.Enabled = true;
                    btnAddClassControlPanel.Enabled = false;
                    btnUpdateClassControlPanel.Enabled = false;
                    btnRefreshClassControlPanel.Enabled = false;
                    txtClassNameClassControlPanel.Enabled = false;
                    txtRoomClassControlPanel.Enabled = false;
                    dtpTimeEndClassControlPanel.Enabled = false;
                    dtpTimeStartClassControlPanel.Enabled = true;
                    dtpTimeStartClassControlPanel.Value = DateTime.Now;
                }
            }
            else
            {
                MessageBox.Show("You must to choose ClassID in Class Treeview", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void cbbTeacherIDClassControlPanel_SelectedValueChanged(object sender, EventArgs e)
        {
            string teacherID = cbbTeacherIDClassControlPanel.SelectedValue.ToString();
            ShowTeacherAvatarClassControlPanel(teacherID);
        }

        private void btnChangeTeacherClassControlPanel_Click(object sender, EventArgs e)
        {
            string preTeacherID = lblCurrentTeacher.Text;
            string nextTeacherID = cbbTeacherIDClassControlPanel.SelectedItem.ToString();
            if (preTeacherID != nextTeacherID)
            {
                DialogResult result = MessageBox.Show("Current Teacher: " + preTeacherID + " => New Teacher: " + nextTeacherID + " ?", "Message Box", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    //update................................
                    UpdateChangeTeacher();
                    dtpTimeSource.Value = dtpTimeStartClassControlPanel.Value;
                }
            }
            else
            {
                MessageBox.Show("You must be choose another teacher", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        // buntton: Cancel Change
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (cbbTeacherIDClassControlPanel.Enabled == true)
            {
                cbbTeacherIDClassControlPanel.Enabled = false;
                btnChangeTeacherClassControlPanel.Enabled = false;
                btnAddClassControlPanel.Enabled = false;
                btnUpdateClassControlPanel.Enabled = false;
                btnRefreshClassControlPanel.Enabled = false;
                txtClassNameClassControlPanel.Enabled = true;
                txtRoomClassControlPanel.Enabled = true;
                dtpTimeEndClassControlPanel.Enabled = true;
                dtpTimeStartClassControlPanel.Enabled = true;

            }
        }
        private void UpdateChangeTeacher()
        {
            string preTeacherID = lblCurrentTeacher.Text;
            string nextTeacherID = cbbTeacherIDClassControlPanel.SelectedItem.ToString();
            string classID = txtClassIDClassControlPanel.Text;
            DateTime timeStart = dtpTimeSource.Value;
            DateTime timeEnd = dtpTimeEndClassControlPanel.Value;
            DateTime timeLine = dtpTimeStartClassControlPanel.Value;
            if (timeLine > timeStart && timeLine < timeEnd)
            {
                Class c = new Class()
                {
                    TeacherID = nextTeacherID,
                    ClassID = classID
                };
                ClassHistory ch1 = new ClassHistory()
                {
                    ClassID = classID,
                    TeacherID = preTeacherID,
                    TeachTimeEnd = timeLine
                };
                ClassHistory ch2 = new ClassHistory()
                {
                    ClassID = classID,
                    TeacherID = nextTeacherID,
                    TeachTimeStart = timeLine
                };
                bool b1 = ClassControl.UpdateClassHistoryNewTeacher(ch1);
                if (b1)
                {
                    bool b2 = ClassControl.InsertClassHistoryNewTeacher(ch2);
                    if (b2)
                    {
                        bool b3 = ClassControl.UpdateClassNewTeacher(c, timeLine);
                        if (b3)
                        {
                            MessageBox.Show("Change Teacher Successful", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            lblCurrentTeacher.Text = cbbTeacherIDClassControlPanel.Text;
                            FillGrvwClassDetail(classID);
                        }
                        else MessageBox.Show("Update Class Failure (3)", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else MessageBox.Show("Insert ClassHistory Failure (2)", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show("Update ClassHistory Failure (1)", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }

            }
            else MessageBox.Show("Time Start is wrong ", "Message Box", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnSearchClass_Click(object sender, EventArgs e)
        {
            string classID = txtClassSearch.Text;
            if (classID.Trim().Length > 0)
            {
                DataTable table = ClassControl.SearchClassByClassID(classID);
                FillLvwClassInformation(table);

            }

        }
        private void txtClassSearch_MouseDown(object sender, MouseEventArgs e)
        {
            txtClassSearch.Text = "";
        }

        private void btnRefreshClass_Click(object sender, EventArgs e)
        {
            DataTable table = ClassControl.GetClassInformation();
            FillLvwClassInformation(table);
        }
        private void EnableStudentControl() {
            if (rbtnClasses.Checked)
            {
                tvwStudentClassID.Visible = true;
                cbbClasses.Enabled = true;
                cbbStudentStatus.Enabled = false;
            }
            else {
                tvwStudentClassID.Visible = false;
                cbbClasses.Enabled = false;
                cbbStudentStatus.Enabled = true;
            }
        }
        private void FillTreeViewStudentClassID()
        {
            tvwStudentClassID.Nodes.Clear();
            List<string> AllID = ClassControl.GetAllClassID();
            tvwStudentClassID.Nodes.Add("All Classes");
            foreach (string classID in AllID)
            {
                tvwStudentClassID.Nodes[0].Nodes.Add(classID);
            }
            tvwStudentClassID.Nodes.Add("Learning Classes");
            List<string> learningIDs = ClassControl.GetClassIDLearning();
            foreach (string classID in learningIDs)
            {
                tvwStudentClassID.Nodes[1].Nodes.Add(classID);
            }
            tvwStudentClassID.Nodes.Add("Waiting Classes");
            List<string> waitingIDs = ClassControl.GetClassIDWaiting();
            foreach (string classID in waitingIDs)
            {
                tvwStudentClassID.Nodes[2].Nodes.Add(classID);
            }
            tvwStudentClassID.Nodes.Add("Finished Classes");
            List<string> finishedIDs = ClassControl.GetClassIDFinished();
            foreach (string classID in finishedIDs)
            {
                tvwStudentClassID.Nodes[3].Nodes.Add(classID);
            }
        }
        private void rbtnClasses_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnClasses.Checked)
            {
                tvwStudentClassID.Visible = true;
                cbbClasses.Enabled = true;
                cbbStudentStatus.Enabled = false;
                FillTreeViewStudentClassID();
                DataTable table = ClassControl.GetClassDetailStudent("");
                grvwStudentControl.DataSource = table;
            }
            else
            {
                tvwStudentClassID.Visible = false;
                cbbClasses.Enabled = false;
                cbbStudentStatus.Enabled = true;
            }
        }

        private void rbtnAllStudent_CheckedChanged(object sender, EventArgs e)
        {
            if (rbtnAllStudent.Checked)
            {
                tvwStudentClassID.Visible = false;
                cbbClasses.Enabled = false;
                cbbStudentStatus.Enabled = true;
                DataTable table = StudentControl.GetAllStudentInDB();
                grvwStudentControl.DataSource = table;
                FillStudentInformation(null);
            }
            else
            {
                tvwStudentClassID.Visible = true;
                cbbClasses.Enabled = true;
                cbbStudentStatus.Enabled = false;
            }
        }

        private void tvwStudentClassID_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = tvwStudentClassID.SelectedNode;
            if (node.Level == 1)
            {
                string classID = node.Text;
                DataTable table = ClassControl.GetClassDetailStudent(classID);
                grvwStudentControl.DataSource = table;
                grvwStudentControl.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            else {
                DataTable table = ClassControl.GetClassDetailStudent("");
                grvwStudentControl.DataSource = table;
                grvwStudentControl.Columns[2].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            }
            
        }

        private void grvwStudentControl_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;
            string studentID = grvwStudentControl.Rows[e.RowIndex].Cells[0].Value.ToString();
            Student s = StudentControl.GetStudentInFormation(studentID);            
            FillStudentInformation(s);
        }
        private void FillStudentInformation(Student s) {
            if (s != null)
            {
                txtStudentID.Text = s.StudentID;
                if (s.Status == "learning")
                {
                    cbbStudentInformationStatus.SelectedItem = "Learning";
                }
                else if (s.Status == "finished")
                {
                    cbbStudentInformationStatus.SelectedItem = "Finished";
                }
                else if (s.Status == "waiting")
                {
                    cbbStudentInformationStatus.SelectedItem = "Waiting";
                }                
                txtStudentName.Text = s.Name;
                string gender = s.Gender;
                if (gender == "male")
                {
                    rbtnStudentMale.Checked = true;
                    rbtnStudentFemale.Checked = false;
                }
                else if (gender == "female")
                {
                    rbtnStudentMale.Checked = false;
                    rbtnStudentFemale.Checked = true;
                }
                dtpStudentBirthday.Value = s.Dob;
                txtStudentEmail.Text = s.Email;
                txtStudentPhone.Text = s.Phone;
                rtxtStudentAddress.Text = s.Address;
            }
            else {
                txtStudentID.Text = "";
                txtStudentEmail.Text = "";
                txtStudentPhone.Text = "";
                rtxtStudentAddress.Text = "";
                txtStudentName.Text = "";
                dtpStudentBirthday.Value = DateTime.Now;
                rbtnStudentMale.Checked = true;
                rbtnStudentFemale.Checked = false;
                cbbStudentInformationStatus.SelectedIndex = 0;
            }
        }

        private void cbbStudentStatus_Click(object sender, EventArgs e)
        {

        }

        
    }
}
